package com.shanghaionstar.mro.util;


import android.content.Context;
import android.location.Location;

import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.map.MapContainerImpl;
import com.onstar.cn.map.MapSearch;
import com.onstar.cn.map.OMapActivity;
import com.onstar.cn.map.OMapView;
import com.onstar.cn.map.common.MapException;
import com.onstar.cn.map.common.PoiItemInfo;
import com.onstar.cn.map.common.PoiType;
import com.onstar.cn.map.common.QueryType;
import com.onstar.cn.map.core.Circle;
import com.onstar.cn.map.core.impl.OGeoPointImpl;
import com.onstar.cn.map.listener.OSearchHandlerListener;
import com.onstar.cn.map.util.QueryOptions;
import com.onstar.cn.vehicle.entity.RequestType;
import com.shanghaionstar.OnstarApplication;
import com.shanghaionstar.enumtype.OperateType;
import com.shanghaionstar.mro.MrOActivity;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.utils.MyLocationUtil;

import java.util.List;

public class MrOPoiUtil {
    public boolean isLocationing = false;
    private Location myLocation = null;
    private MyLocationUtil mMyLoationUtil = null;
    private MapContainerImpl mapContainer;

//    private Context context;
    private MapSearch mapsearch;
    private MrOActivity.OnMroOperationCallbackListener operationCallbackListener;
    private String keyPlace;
    private String currCity;
    private MrOLocationResult mrOLocationResult;


    public void setMyLocation(Location myLocation) {
        this.myLocation = myLocation;
    }

//    private static class MrOPoiUtilInner {
//        static MrOPoiUtil poiUtil = new MrOPoiUtil();
//    }

    public MrOPoiUtil() {
    }

//    private MrOActivity activity;
//
//    public MrOPoiUtil(MrOActivity activity) {
//        this.activity = activity;
//    }

//    public  MrOPoiUtil getInstance() {
//        return MrOPoiUtilInner.poiUtil;
//    }

//    public MrOPoiUtil refreshActivity(MrOActivity activity) {
//        this.activity = activity;
//        return this;
//    }

//    Handler mHandler = new Handler() {
//        public void handleMessage(Message msg) {
//            String errorMsg = "";
//            switch (msg.what) {
//                case Constants.SENDTOCAR_PROGRESS:
////				AlertDialogUtil.showAlertDialog(mroActivity, mroActivity.getString(R.string.poi_destination_title_str),
////						mroActivity.getString(R.string.send_to_tbt_progress));
////				String requestId = msg.getData().getString("requestId");
////				PoiItemInfo poiItemInfo = (PoiItemInfo) msg.getData().getSerializable("poiItemInfo");
////				saveHistoryToSql(requestId, poiItemInfo);
////				PollingStatusUtil.startPollingTask(mroActivity.getParent(), requestId, RequestType.SendToTBTRequest,true);
//                    //mroActivity.testTBT();
//                    break;
//                case Constants.SENDTOCAR_ERROR:
//                    ErrorInfo errorInfo = (ErrorInfo) msg.getData().getSerializable("errorInfo");
//                    String startTime = msg.getData().getString("startTime_sendToCar");
////				BusinessUtil.updateOperateStatues(RequestType.SendToTBTRequest, false);
////				ErrorCodeUtil.ShowErrorOnsMsg(mroActivity, errorInfo, RequestType.SendToTBTRequest);
//                    operateReport(RequestType.SendToTBTRequest, OperateType.FAILURE, startTime);
//                    errorMsg = ErrorCodeUtil.getErrorMsgByCode(context, errorInfo);
//                    if(errorInfo!=null) {
//                        OperateB2CUtil.operateEventReport(Event.Connect, errorInfo.getCode() + "," + errorMsg, context, "2");
//                    }
////				CommonUtil.operateB2CReport(EvenTt.Connect, errorInfo.getCode() + "," + errorMsg, mroActivity);//report
//                    break;
//            }
//        }
//
//    };


    private OSearchHandlerListener searchListener = new OSearchHandlerListener() {

        @Override
        public void OnSearchResults(long id, QueryType type, List<PoiItemInfo> results, int pageIndex, int totalPages) {
            if (operationCallbackListener != null) {
                operationCallbackListener.onPOICallbackListener(results, keyPlace, type);
            }
        }

        @Override
        public void OnSearchErrors(long id, MapException mapExp) {
            if (operationCallbackListener != null) {
                operationCallbackListener.onPOICallbackListener(null, keyPlace, null);
            }
        }

        @Override
        public void OnReverseResults(long id, PoiItemInfo poi) {
        }
    };

    public void searchByName(String key, String cityCode, MrOActivity.OnMroOperationCallbackListener operationCallbackListener, OMapActivity mapActivity) {
//        context = mapActivity;
        if (mapsearch == null) {
            mapsearch = new MapSearch(mapActivity, null);
            mapsearch.registerSearchListener(searchListener);
        }
        keyPlace = key;
        this.operationCallbackListener = operationCallbackListener;
        QueryOptions options = new QueryOptions();
        mapsearch.searchByName(key, PoiType.All, cityCode, options);
    }

    public void searchNearBy(final String key, final String cityCode, final MrOActivity.OnMroOperationCallbackListener operationCallbackListener, final OMapActivity mapActivity) {
//        context = mapActivity;
        if (mapsearch == null) {
            mapsearch = new MapSearch(mapActivity, null);
            mapsearch.registerSearchListener(searchListener);
        }
        keyPlace = key;
        this.operationCallbackListener = operationCallbackListener;
        isLocationing = true;
        mrOLocationResult = new MrOLocationResult() {
            @Override
            public void onResult(Location location) {
                if (location != null) {
                    QueryOptions options = new QueryOptions();
                    OGeoPointImpl pt = new OGeoPointImpl(myLocation.getLatitude(), myLocation.getLongitude());
                    Circle circle = new Circle(50 * 1000, pt);
                    options.setCircle(circle);
                    mapsearch.searchNearBy(key, PoiType.All, cityCode, options);
                } else {
                    searchByName(key, cityCode, operationCallbackListener, mapActivity);
                }
                mrOLocationResult = null;
            }
        };
        mMyLoationUtil.initMyLocation();
    }

    private void operateReport(RequestType requestType, OperateType operateType, String startTime) {
//        FunctionNameFindId fnfi = FunctionNameFindId.GetVehicleLocationButton;
//        OperateType ot = OperateType.SUCCESS;
//        if (null != operateType)
//            ot = operateType;
//        if (requestType.equals(RequestType.GetCurrentLocationRequest)) {
//            fnfi = FunctionNameFindId.GetVehicleLocationButton;
//        } else if (requestType.equals(RequestType.SendToTBTRequest)) {
//            fnfi = FunctionNameFindId.SendToVehicleButton;
//        }
//        if (operateType != OperateType.FAILURE || operateType != OperateType.SUCCESS) {
//            startTime = "";
//        }
////		ReportBusiness reportBusiness = ReportBusiness.getInstance(mroActivity);
////		reportBusiness.operateReport(fnfi, ot, startTime, false);
//        BusinessUtil.sendReportByClickType(context, fnfi.getStringValue());
////		CommonUtil.operateB2CReport(fnfi.getStringValue(), mroActivity);
    }

    public String getCurrCity() {
        return currCity;
    }

    public void setCurrCity(String currCity) {
        this.currCity = currCity;
    }

    public Location getMyLocation() {
        return myLocation;
    }

    public void getMyLocationFromPhone(OMapView mapView, final MrOActivity mroActivity) {
        mapContainer = new MapContainerImpl(mroActivity, mapView.getMap(), null);
        mapContainer.registerMapSearchListener(new OSearchHandlerListener() {
            @Override
            public void OnSearchResults(long id, QueryType type, List<PoiItemInfo> results, int pageIndex,
                                        int totalPages) {
            }

            @Override
            public void OnSearchErrors(long id, MapException mapExp) {

            }

            @Override
            public void OnReverseResults(long id, PoiItemInfo poi) {
                currCity = poi.getCityName();

                //保存用户当前的城市名称信息
                if (myLocation != null) {
                    Context context = OnstarApplication.getApplication();
                    PreferencesUtls.getInstance(context).putString(FinalConstants.SharedPreferencesConfig.USER_CURRENT_CITY_INFO, currCity);
                    PreferencesUtls.getInstance(context).putString(FinalConstants.SharedPreferencesConfig.USER_CURRENT_LOCATION_LATITUDE, String.valueOf(myLocation.getLatitude()));
                    PreferencesUtls.getInstance(context).putString(FinalConstants.SharedPreferencesConfig.USER_CURRENT_LOCATION_LONGITUDE, String.valueOf(myLocation.getLongitude()));
                }
            }
        });


        MyLocationUtil.LocationResult locationResult = new MyLocationUtil.LocationResult() {
            @Override
            public void gotLocation(Location location) {
//				Message message = handler.obtainMessage();
                if (location == null) {
                    isLocationing = false;
//					message.what = Constants.MY_LOCATION_NULL;
                } else {
                    myLocation = location;
                    double latitude = location.getLatitude();
                    double longitude = location.getLongitude();
                    // 根据经纬度获取城市
                    mapContainer.geoCoderGps(latitude, longitude);
//					message.what = Constants.MY_LOCATION_NOT_NULL;
                }
                if (isLocationing) {
                    isLocationing = false;
//					handler.sendMessage(message);
                }
                if (mrOLocationResult != null) {
                    mrOLocationResult.onResult(location);
                }
            }
        };

        if (mMyLoationUtil == null) {
            mMyLoationUtil = new MyLocationUtil(mroActivity, locationResult);

        }
        isLocationing = true;
        mMyLoationUtil.initMyLocation();
    }

//    public void sendToTBT(final PoiItemInfo poiItemInfo, Handler handler) {//zengshuai
////        BusinessUtil.sendReportByClickType(context, FunctionNameFindId.SendToTBT.getStringValue());
//        if (ApplicationUtil.getInstance().isLogin()) {
//            if (!BusinessUtil.checkDriverOrProxyAndShowDialog(activity)) {
//                return;
//            }
////            if (!BusinessUtil.isServiceEntitlement(context, Constants.ENTITLEMENT_M05NAVIGATION)) {
////                AlertDialogUtil.showAlertDialog(context, context.getString(R.string.dialog_warning),
////                        context.getString(R.string.SB002_MSG001));
////                return;
////            }
//            if(!BusinessUtil.checkPackageRight(Constants.ENTITLEMENT_M05NAVIGATION, activity,true)) {
//                return;
//            }
//
////			if (!BusinessUtil.checkDriverOrProxyAndShowDialog(context)) {
////				return;
////			}
//            if (BusinessUtil.checkInProgressCommand(context, null)) {
////				AlertDialogUtil.showAlertDialog(context, context.getString(R.string.dialog_warning),
////						context.getString(R.string.service_inProcess_alert));
//                BusinessUtil.updateConfigValue(FinalConfigParams.SHARE_DESTINATION, "-1", context);
//                return;
//            }
//            initSendToCar(RemoteCommandsType.COMMANDS_TBT_ROUTE, poiItemInfo, handler);
//        } else if (ApplicationUtil.getInstance().isAutoLogings()) {
//            AlertDialogUtil.showAlertDialog(context, context.getString(R.string.dialog_warning),
//                    context.getString(R.string.loading));
//        }
//    }
//
//    public void sendToODD(final PoiItemInfo poiItemInfo, Handler handler) {//zengshuai
////        BusinessUtil.sendReportByClickType(context, FunctionNameFindId.SendToTBT.getStringValue());
//        if (ApplicationUtil.getInstance().isLogin()) {
//            if (!BusinessUtil.checkDriverOrProxyAndShowDialog(activity)) {
//                return;
//            }
////            if (!BusinessUtil.isServiceEntitlement(context, Constants.ENTITLEMENT_M05NAVIGATION)) {
////                AlertDialogUtil.showAlertDialog(context, context.getString(R.string.dialog_warning),
////                        context.getString(R.string.SB002_MSG001));
////                return;
////            }
//            if(!BusinessUtil.checkPackageRight(Constants.ENTITLEMENT_M05NAVIGATION, context,true)) {
//                return;
//            }
//
////			if (!BusinessUtil.checkDriverOrProxyAndShowDialog(context)) {
////				return;
////			}
//            if (BusinessUtil.checkInProgressCommand(context, null)) {
////				AlertDialogUtil.showAlertDialog(context, context.getString(R.string.dialog_warning),
////						context.getString(R.string.service_inProcess_alert));
//                BusinessUtil.updateConfigValue(FinalConfigParams.SHARE_DESTINATION, "-1", context);
//                return;
//            }
//            initSendToCar(RemoteCommandsType.COMMANDS_NAV_DESTINATION, poiItemInfo, handler);
//        } else if (ApplicationUtil.getInstance().isAutoLogings()) {
//            AlertDialogUtil.showAlertDialog(context, context.getString(R.string.dialog_warning),
//                    context.getString(R.string.loading));
//        }
//    }






//    private void initSendToCar(final RemoteCommandsType commandsType, final PoiItemInfo poiItemInfo, Handler handler) {
////    	getLogger().d(
////				"Method initSendToCar() poiItemInfo:" + poiItemInfo.getCityName() + "latitude:"
////						+ poiItemInfo.getLatitude() + "longitude:" + poiItemInfo.getLongitude());
//        Message msg = Message.obtain();
//        msg.what = Constants.SHOW_TBT_PROGRESS;
//        handler.sendMessage(msg);
//
////        final PoiUtil poiUtil = new PoiUtil(context, poiItemInfo, handler);
//        // 超时重新请求token
////        AuthorizeUtil authUtils = new AuthorizeUtil(context);
////        authUtils.setResultListener(new AuthorResultListener() {
////
////            @Override
////            public void onSuccess(AuthorizeType type) {
////                switch (type) {
////                    case PINREAUTHORIZE:
////                        poiUtil.command(commandsType);
////                        break;
////                    default:
////                        break;
////                }
////
////            }
////
////            @Override
////            public void onFail(AuthorizeType type, final HttpException e) {
////                switch (type) {
////                    case PINREAUTHORIZE:
////                        AlertDialogUtil.showDialogByExceptionCode(context, e);
////                        break;
////                    default:
////                        break;
////                }
////
////            }
////        });
////        if (BusinessUtil.checkTokenExpired(context)) {
////            AuthTokenRequestEntity entity = BusinessUtil.createAuthTokenRequestEntity();
//////            authUtils.pinReauthenticationForNoPin(entity);
////        } else {
////            MroPoiPresenter presenter = new MroPoiPresenter(context);
////            presenter.sendTbtOrOdd(poiItemInfo);
//////            poiUtil.command(commandsType);
////        }
//    }

    private interface MrOLocationResult {
        void onResult(Location location);
    }
}
